package cn.stronglink.esm27.collection.iot.devices.esm27.task;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.google.common.util.concurrent.AbstractScheduledService;

import cn.stronglink.esm27.collection.iot.devices.esm27.ESM27Server;

public class AutoPushSensorDataService extends AbstractScheduledService {
//	private static Logger logger = LogManager.getLogger(AutoPushSensorDataService.class.getName());
	private static final int SEND_DATA_SPAN_MILLISECOND = 3500;
	private int sendSpan = SEND_DATA_SPAN_MILLISECOND;
	private long cron = 60;
	private List<Integer> deviceIds;
	private static final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
	private ESM27Server esm27Server; // esm27服务器

	public AutoPushSensorDataService(ESM27Server esm27Server, List<Integer> deviceIds, long cron, int sendSpan) {
		this.deviceIds = deviceIds;
		this.sendSpan = Math.max(sendSpan, SEND_DATA_SPAN_MILLISECOND);
		this.cron = Math.max(cron, this.sendSpan * (this.deviceIds.size() + 1));
		this.esm27Server = esm27Server;
	}

	@Override
	protected void runOneIteration() throws Exception {
		int i = 0;
		// 发送风力请求
		timer.schedule(new PushWindTimer(esm27Server), 0, TimeUnit.SECONDS);

		for (i = 0; i < deviceIds.size(); i++) {
			Integer id = deviceIds.get(i);
			timer.schedule(new PushGasTimer(esm27Server, id.byteValue()),
					AutoPushSensorDataService.this.sendSpan * (i + 1), TimeUnit.MILLISECONDS);
		}

	}

	@Override
	protected Scheduler scheduler() {
		return Scheduler.newFixedDelaySchedule(1, cron, TimeUnit.MILLISECONDS);
	}

}
